import  { useState, useEffect } from 'react';
import { 
  Form, Input, Select, DatePicker, 
  Button, Space, Card, Divider, 
  message, Row, Col, InputNumber
} from 'antd';
import { 
  CheckOutlined, CalendarOutlined, 
  UserOutlined, ClockCircleOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';  // 替换moment为dayjs
import "./appointment.css";

// 服务项目列表
const serviceOptions = [
  { value: 'tuina', label: '推拿按摩', price: 188 },
  { value: 'zhenjiu', label: '针灸治疗', price: 268 },
  { value: 'aijiu', label: '艾灸养生', price: 228 },
  { value: 'baguan', label: '拔罐疗法', price: 168 },
  { value: 'zhongyao', label: '中药熏蒸', price: 298 }
];

// 员工列表
const doctorOptions = [
  { value: 'li', label: '李员工' },
  { value: 'chen', label: '陈员工' },
  { value: 'zhao', label: '赵员工' },
  { value: 'wang', label: '王员工' }
];

// 状态选项
const statusOptions = [
  { value: 'booked', label: '已预约' },
  { value: 'confirmed', label: '已确认' },
  { value: 'ongoing', label: '进行中' },
  { value: 'completed', label: '已完成' },
  { value: 'cancelled', label: '已取消' }
];

// 时间段选项（每小时一个时段）
const times = [];
for (let hour = 9; hour <= 18; hour++) {
  const nextHour = hour + 1;
  times.push({
    value: `${hour.toString().padStart(2, '0')}:00 - ${nextHour.toString().padStart(2, '0')}:00`,
    label: `${hour.toString().padStart(2, '0')}:00 - ${nextHour.toString().padStart(2, '0')}:00`
  });
}

const UpdateAppointment = (props) => {
  // 从props中解构所需数据
  const { 
    id, 
    customer,  
    service, 
    doctor, 
    date, 
    time, 
    price: initialPrice, 
    status,
    onFormChange, // 用于通知父组件表单变化的回调
  } = props.data;
  

  const [form] = Form.useForm();
  const [currentPrice, setCurrentPrice] = useState(initialPrice || 0);
  const [loading, setLoading] = useState(false);

  // 初始化表单数据
  useEffect(() => {
    // 转换服务项目为对应的值
    const serviceItem = serviceOptions.find(
      item => item.label === service
    );
    
    // 转换员工为对应的值
    const doctorItem = doctorOptions.find(
      item => item.label === doctor
    );
    
    // 设置表单值，使用dayjs处理日期
    form.setFieldsValue({
      id,
      name:customer.name,
      customerPhone: customer.phone,
      service: serviceItem ? serviceItem.value : '',
      doctor: doctorItem ? doctorItem.value : '',
      date: date ? dayjs(date) : null,  
      time,
      price: initialPrice ? parseFloat(initialPrice) : 0,
      status,
      notes: ''
    });
    
    // 设置价格
    if (serviceItem) {
      setCurrentPrice(serviceItem.price);
    }
  }, [id, customer.name, customer.phone, service, doctor, date, time, initialPrice, status, form]);

  // 服务项目变更时更新价格
  const handleServiceChange = (value) => {
    const serviceItem = serviceOptions.find(item => item.value === value);
    if (serviceItem) {
      setCurrentPrice(serviceItem.price);
      form.setFieldsValue({ price: serviceItem.price });
      
      // 通知父组件表单变化
      if (onFormChange) {
        onFormChange({
          ...getCurrentFormValues(),
          service: serviceItem.label,
          price: serviceItem.price
        });
      }
    }
  };

  // 获取当前表单值
  const getCurrentFormValues = () => {
    try {
      return form.getFieldsValue();
    } catch (error) {
      return {};
    }
  };

  // 表单字段变化时通知父组件
  const handleFieldChange = () => {
    if (onFormChange) {
      const values = getCurrentFormValues();
      const serviceItem = serviceOptions.find(item => item.value === values.service);
      const doctorItem = doctorOptions.find(item => item.value === values.doctor);
      
      onFormChange({
        ...values,
        service: serviceItem ? serviceItem.label : '',
        doctor: doctorItem ? doctorItem.label : '',
        date: values.date ? values.date.format('YYYY-MM-DD') : '',  
        price: values.price
      });
    }
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();
      
      // 格式化提交数据
      const serviceItem = serviceOptions.find(item => item.value === values.service);
      const doctorItem = doctorOptions.find(item => item.value === values.doctor);
      
      const formData = {
        id: values.id,
        name: values.name,
        customerPhone: values.customerPhone,
        service: serviceItem ? serviceItem.label : '',
        doctor: doctorItem ? doctorItem.label : '',
        date: values.date ? values.date.format('YYYY-MM-DD') : '',  
        time: values.time,
        price: values.price.toFixed(2),
        status: values.status,
        notes: values.notes
      };
      
    console.log(formData)
      
    } catch (errorInfo) {
      console.error('Validation failed:', errorInfo);
      message.error('表单验证失败，请检查输入内容');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="modal-box">
      {/* <Typography.Title level={4} className="modal-title">
        编辑预约 <span className="appointment-id">{id}</span>
      </Typography.Title> */}
      
      <Divider style={{ margin: '16px 0' }} />
      
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          status: 'booked',
          price: 0
        }}
        onValuesChange={handleFieldChange}
      >
        {/* 预约基本信息 */}
        <Card className="form-card" title="预约基本信息" variant={true}>
          <Form.Item
            name="id"
            label="预约编号"
            rules={[{ required: true, message: '请输入预约编号' }]}
          >
            <Input disabled style={{ backgroundColor: '#f5f5f5' }} />
          </Form.Item>
          
          <Row gutter={16}>
            <Col xs={24} sm={12}>
              <Form.Item
                name="name"
                label="客户姓名"
                rules={[{ required: true, message: '请输入客户姓名' }]}
              >
                <Input prefix={<UserOutlined />} placeholder="请输入客户姓名" />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item
                name="customerPhone"
                label="联系电话"
                rules={[
                  { required: true, message: '请输入联系电话' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
                ]}
              >
                <Input placeholder="请输入客户手机号码" maxLength={11} />
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item
            name="status"
            label="预约状态"
            rules={[{ required: true, message: '请选择预约状态' }]}
          >
            <Select 
              placeholder="请选择预约状态" 
              options={statusOptions}
              style={{ width: '100%' }}
            />
          </Form.Item>
        </Card>
        
        {/* 服务信息 */}
        <Card className="form-card" title="服务详情" variant={true} style={{ marginTop: 16 }}>
          <Row gutter={16}>
            <Col xs={24} sm={12}>
              <Form.Item
                name="service"
                label="理疗项目"
                rules={[{ required: true, message: '请选择理疗项目' }]}
              >
                <Select 
                  placeholder="请选择理疗项目" 
                  options={serviceOptions}
                  onChange={handleServiceChange}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
         
            <Col xs={24} sm={12}>
                  <Form.Item
            name="price"
            label="服务价格"
            rules={[{ required: true, message: '请输入服务价格' }]}
          >
            <InputNumber
            //   prefix="¥"
              min={0}
              step={0.01}
              formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
              parser={value => value.replace(/\¥\s?|(,*)/g, '')}
              style={{ width: '100%' }}
            />
          </Form.Item>
            </Col>
             {/* <Form.Item
                name="doctor"
                label="接诊员工"
                rules={[{ required: true, message: '请选择接诊员工' }]}
              >
                <Select 
                  placeholder="请选择接诊员工" 
                  options={doctorOptions}
                  style={{ width: '100%' }}
                />
              </Form.Item> */}
          </Row>
          
          <Row gutter={16}>
            <Col xs={24} sm={12}>
              <Form.Item
                name="date"
                label="预约日期"
                rules={[{ required: true, message: '请选择预约日期' }]}
              >
                <DatePicker 
                  placeholder="选择预约日期" 
                  style={{ width: '100%' }}
                  // 使用dayjs处理禁用日期逻辑
                  disabledDate={(current) => current && current < dayjs().subtract(1, 'day')}
                  prefix={<CalendarOutlined />}
                />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item
                name="time"
                label="预约时段"
                rules={[{ required: true, message: '请选择预约时段' }]}
              >
                <Select 
                  placeholder="请选择预约时段" 
                  options={times}
                  style={{ width: '100%' }}
                  prefix={<ClockCircleOutlined />}
                />
              </Form.Item>
            </Col>
          </Row>
          
        
        </Card>
        
        {/* 备注信息 */}
        <Card className="form-card" title="备注信息" variant={true} style={{ marginTop: 16 }}>
          <Form.Item
            name="notes"
            label="备注"
          >
            <Input.TextArea rows={4} placeholder="请输入备注信息（如客户特殊情况、注意事项等）" />
          </Form.Item>
        </Card>
        
        {/* 操作按钮 */}
        <div className="modal-actions">
          <Space size="middle">
        
            <Button 
              type="primary" 
              icon={<CheckOutlined />} 
              onClick={handleSubmit}
              loading={loading}
              
              className="save-btn"
            >
              保存修改
            </Button>
          </Space>
        </div>
      </Form>
    </div>
  );
};

export default UpdateAppointment;
